package programe

import (
	"awesomeTask/application/client"
	"awesomeTask/application/resource"
	"awesomeTask/application/variable"
	awesomeTask "awesomeTask/commom"
	"awesomeTask/commom/ListHelper"
	"awesomeTask/system/helper"
	"regexp"
	"strconv"
	"strings"
)

const TABLE_NAME = "programe_source"
const PROJECT_TABLE_NAME = "t_project"

func EditPrograme(filename string, content string, dirname string, project_id string, id string, create_uid string, update_uid string, pid string, create_time string) bool {
	insertInfo := map[string]interface{}{
		"filename":        filename,
		"programe_source": content,
		"programe_uuid":   helper.Md5(content),
		"dirname":         dirname,
		"pid":             pid,
		"update_time":     awesomeTask.Now(),
		"project_id":      project_id,
		"create_uid":      create_uid,
		"update_uid":      update_uid,
		"create_time":     create_time,
	}
	if id != "" {
		insertInfo["id"] = id
	}
	if awesomeTask.InsertOrUpdate(TABLE_NAME, insertInfo) {
		projectDir := GetDirname(pid, project_id)
		resource.EditResourceCode(projectDir, filename, content)
		for _, i := range client.Nodes {
			resource.ManagerObj{}.DistributeSource(i.Connetion, content, projectDir+"/"+filename)
		}
		return true
	}

	return false
}
func getParent(pid string, data []map[string]interface{}) string {
	for _, item := range data {
		if strconv.Itoa(int(item["id"].(int64))) == pid {
			parent_dir := getParent(strconv.Itoa(int(item["pid"].(int64))), data)
			return parent_dir + "/" + item["dirname"].(string) + "/"
		}
	}
	return ""
}
func GetprojectNameByProjectId(projectId string) string {
	return awesomeTask.Query("select project_uname from "+PROJECT_TABLE_NAME+" where id=?", projectId)[0]["project_uname"].(string)
}
func GetDirname(pid string, project_id string) string {
	data := awesomeTask.Query("select id,dirname,pid from "+TABLE_NAME+" where project_id=?", project_id)
	project_uname := awesomeTask.Query("select project_uname from "+PROJECT_TABLE_NAME+" where id=?", project_id)[0]["project_uname"]
	dirname := project_uname.(string) + "/" + variable.ApplicationPath + "/" + getParent(pid, data)
	return strings.ReplaceAll(dirname, "//", "/")
}

/**
获取详细信息
*/
func GetProgrameById(id string) interface{} {
	data := awesomeTask.Query("select id,filename,programe_source,project_id,pid,update_time,create_time,dirname,is_dir from "+TABLE_NAME+" where id=?", id)
	return map[string]interface{}{
		"data": data[0],
	}
}
func findChildrens(pid int64, project_id int64, data []map[string]interface{}) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	for _, item := range data {
		if item["pid"].(int64) == pid && item["project_id"].(int64) == project_id {
			item["children"] = findChildrens(item["id"].(int64), project_id, data)
			item["title"] = getTitle(item["dirname"].(string), item["filename"].(string), item["is_dir"].(int64))
			item["key"] = strconv.Itoa(int(project_id)) + "_" + strconv.Itoa(int(pid)) + "_" + strconv.Itoa(int(item["id"].(int64)))
			if int64(item["is_dir"].(int64)) == 1 {
				item["key"] = item["key"].(string) + "_1"
				item["is-leaf"] = false
			} else {
				item["key"] = item["key"].(string) + "_0"
				item["is-leaf"] = true
			}
			res = append(res, item)
		}
	}
	return res
}
func GetProgrameBeTree(data []map[string]interface{}) []map[string]interface{} {
	project_ids := ListHelper.GetColumn(data, "id")
	whereString, whereInParams := awesomeTask.WhereIn(project_ids)
	programesData := awesomeTask.Query("select project_id,id,filename,dirname,pid,is_dir from "+TABLE_NAME+" where project_id in "+whereString, whereInParams...)
	for index, item := range data {
		children := findChildrens(0, item["id"].(int64), programesData)
		if len(children) > 0 {
			item["children"] = children
		}
		item["is_dir"] = 1
		item["key"] = strconv.Itoa(int(item["id"].(int64))) + "_0_0_1"
		data[index] = item
	}
	return data
}
func getTitle(dirname string, filename string, isDir int64) string {
	if isDir == 1 {
		return dirname
	}
	return filename
}

func GetTaskBaseInfo(id string) map[string]interface{} {
	data := awesomeTask.Query("select filename,pid,project_id from "+TABLE_NAME+" where id=?", id)[0]
	project_name := GetprojectNameByProjectId(strconv.Itoa(int(data["project_id"].(int64))))
	modulePath := GetDirname(strconv.Itoa(int(data["pid"].(int64))), strconv.Itoa(int(data["project_id"].(int64))))
	modulePath = strings.ReplaceAll(modulePath, "//", ".")
	modulePath = strings.ReplaceAll(modulePath, "/", ".")
	modulePath = modulePath + "." + strings.ReplaceAll(data["filename"].(string), ".py", "")
	modulePath = strings.ReplaceAll(modulePath, "..", ".")
	regx, err := regexp.Compile("^" + project_name + "\\.")
	if err != nil {
		panic(err)
	}
	modulePath = regx.ReplaceAllString(modulePath, "")
	return map[string]interface{}{
		"module":       modulePath,
		"project_name": GetprojectNameByProjectId(strconv.Itoa(int(data["project_id"].(int64)))),
		"taskId":       id,
	}
}
